package com.level.restful.util;

//如果JDK版本是1.8，可使用原生Base64类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.level.restful.entity.SysMsgPhone;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

//如果JDK版本低于1.8，请使用三方库提供Base64类

/**
 * @author
 *
 * 发送短信工具类
 */
public class SendMessageUtil {

    //用于格式化鉴权头域，给“X-WSSE”参数赋值
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    //用于格式化鉴权头域，给“Authorization”参数赋值
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";

    public static void main(String[] args) throws Exception{

        //开发准备：APP接入地址 + 接口访问URI
        String url = "https://api.rtc.huaweicloud.com:10443/sms/batchSendSms/v1";
        //开发准备：APP_Key
        String appKey = "nR40JE3A8D3NU1dH73C1x1tgOi8I";
        //开发准备：APP_Secret
        String appSecret = "ec8EXJ37B9CS1X7DtBp80tu5VrZU";

        //开发准备：签名通道号8819080940216 \1069100121280390
        String sender = "8819080940216";
//        String sender = "8819080940182";
        //填写短信接收人号码，多个号码之间用英文逗号分隔
        String receiver = "+8618167141229";
        //状态报告接收地址，为空或者不填表示不接收状态报告
        String statusCallBack = "";

        //开发准备：模板ID
        String templateId = "13a219061d6b47e582661ba372b482ae";
        //模板变量请务必根据实际情况修改，查看更多模板变量规则
        //如模板内容为“您有${NUM_2}件快递请到${TXT_32}领取”时，templateParas可填写为[\"3\",\"人民公园正门\"]
        //双变量示例：String templateParas = "[\"3\",\"人民公园正门\"]";
        String  a="123456";
        String templateParas = "["+a+"]";
//        String  date="2019-09-18";
//        String  time="10:45";
//        String  dep="心内科贾";
//        String doc = "贾医生";
//        String  num = "123456";
//        String  templateParas = "['"+date+"','"+time+"','"+dep+"','"+doc+"','"+num+"']";
//        String  templateParas = "['2019/09/18']";

        //请求Body
        String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack);
//        String body = buildRequestBody(sender, receiver, templateId, getTemplateParas(date,time,dep,doc), statusCallBack);
        System.out.println("body is " + body);

        //请求Headers中的X-WSSE参数值
        String wsseHeader = buildWsseHeader(appKey, appSecret);
        System.out.println("wsse header is " + wsseHeader);

        //如果JDK版本低于1.8，可使用如下代码
//        CloseableHttpClient client = HttpClients.custom()
//                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//                    @Override
//                    public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
//                        return true;
//                    }
//                }).build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();

//        如果JDK版本是1.8，可使用如下代码
        CloseableHttpClient client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .build();

        HttpResponse response = client.execute(RequestBuilder.create("POST")
                .setUri(url)
                .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                .addHeader("X-WSSE", wsseHeader)
                .setEntity(new StringEntity(body)).build());

        System.out.println(response.toString());
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    public static Map<String,Object> sendMsg(SysMsgPhone sysMsgPhone, String mobile, String organName,Map<String,String> map) throws Exception{
        Map<String,Object> resultMap = new HashMap<>();
        //开发准备：APP接入地址 + 接口访问URI
        String url = sysMsgPhone.getAppUrl();
        //开发准备：APP_Key
        String appKey =sysMsgPhone.getAppKey();
        //开发准备：APP_Secret
        String appSecret = sysMsgPhone.getAppSecret();

        //开发准备：签名通道号
        String sender = sysMsgPhone.getSender();
        //填写短信接收人号码，多个号码之间用英文逗号分隔
        String receiver = "+86"+mobile;
        //状态报告接收地址，为空或者不填表示不接收状态报告
        String statusCallBack = "";

        //开发准备：模板ID
        String templateId = sysMsgPhone.getTemplateId();
        //模板变量请务必根据实际情况修改，查看更多模板变量规则
        //如模板内容为“您有${NUM_2}件快递请到${TXT_32}领取”时，templateParas可填写为[\"3\",\"人民公园正门\"]
        //双变量示例：String templateParas = "[\"3\",\"人民公园正门\"]";

        String templateParas ="";
        int randNumber=0;
        if(sysMsgPhone.getDemoId().equalsIgnoreCase("1001")){
            Random rand = new Random();
            randNumber =rand.nextInt(999999);
            templateParas="["+randNumber+"]";
        }
        if(sysMsgPhone.getDemoId().equalsIgnoreCase("1002")){
            templateParas = getTemplateParas(map.get("date"),map.get("time"),map.get("dep"),map.get("doc"),
                    map.get("num"));
        }

        if(sysMsgPhone.getDemoId().equalsIgnoreCase("1003")){
            templateParas = getTemplateParas(map.get("date"),map.get("time"),map.get("dep"),map.get("doc"));
        }
        //请求Body
        String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack);

        //请求Headers中的X-WSSE参数值
        String wsseHeader = buildWsseHeader(appKey, appSecret);

        //如果JDK版本是1.8，可使用如下代码
        CloseableHttpClient client = HttpClients.custom()
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                        (x509CertChain, authType) -> true).build())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();

        //请求方法POST
        HttpResponse response = client.execute(RequestBuilder.create("POST")
                .setUri(url)
                .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                .addHeader("X-WSSE", wsseHeader)
                .setEntity(new StringEntity(body)).build());


        String resstr =EntityUtils.toString(response.getEntity());
        JSONObject jb = JSON.parseObject(resstr);
        String code =jb.getString("code");
        String result =  jb.getString("result");
        String description = jb.getString("description");
        resultMap.put("code", code);
        resultMap.put("result", result);
        resultMap.put("description", description);
        resultMap.put("randNum", randNumber);
        return resultMap;


    }

    static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
                                   String statusCallbackUrl) {

        List<NameValuePair> keyValues = new ArrayList<NameValuePair>();

        keyValues.add(new BasicNameValuePair("from", sender));
        keyValues.add(new BasicNameValuePair("to", receiver));
        keyValues.add(new BasicNameValuePair("templateId", templateId));
        keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));

        //如果JDK版本是1.6，可使用：URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
        return URLEncodedUtils.format(keyValues, StandardCharsets.UTF_8);
    }

    static String buildWsseHeader(String appKey, String appSecret) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String time = sdf.format(new Date());
        String nonce = UUID.randomUUID().toString().replace("-", "");

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes());
        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }

    /**
     *
     * @param date 日期
     * @param time 时间
     * @param dep 科室名称
     * @param doc 医生名
     * @param num 取号密码
     * @return
     */
    private static String getTemplateParas(String  date, String  time, String  dep, String doc, String  num){
        StringBuffer templateParas = new StringBuffer("['");
        templateParas.append(date.replaceAll("-","/")+"','");
        templateParas.append(time+"','");
        templateParas.append(dep+"','");
        templateParas.append(doc+"','");
        templateParas.append(num+"']");
        System.out.println("templateParas.toString() " + templateParas.toString());
        return templateParas.toString();
    }
    /**
     *
     * @param date 日期
     * @param time 时间
     * @param dep 科室名
     * @param doc 医生名
     * @return
     */
    private static String getTemplateParas(String  date, String  time, String  dep, String doc){
        StringBuffer templateParas = new StringBuffer("['");
        templateParas.append(date.replaceAll("-","/")+"','");
        templateParas.append(time+"','");
        templateParas.append(dep+"','");
        templateParas.append(doc+"']");
        System.out.println("templateParas.toString() " + templateParas.toString());
        return templateParas.toString();
    }
}